#include "spellchecker.hpp"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char **argv) {
  if (argc <= 2) {
	cout << "Not enough files!" << endl;
	cout << "  Usage: " << argv[0] << "infile outfile" << endl;
	return 1;
  }

  ifstream text(argv[1]);
  if (!text.is_open()) {
	cout << "Cannot find file: " << argv[1] << endl;
	return 2;
  }

    
  ofstream ofile(argv[2]);
  if (!ofile.is_open()) {
	cout << "Cannot open file: " << argv[2] << endl;
	return 2;
  }

  Spellchecker sp;

  string str;
  ifstream dict("dictionary.txt");

  if (dict.is_open()) {
	while (dict.good()) {
      getline(dict, str);
      
      string cor = "";
      for (int i=0; i<str.size(); i++) {
		if (sp.index(str[i]) != -1) {
          cor += str[i];
		} else {
          break;
		}
      }
      sp.insert(cor);
	}
  }

  dict.close();

  
  while(text.good()) {
	str.clear();
	getline(text, str);

	string s;
	string cr;
	for (int i=0; i<str.size(); i++) {
      bool flag = true;
      if (sp.index(str[i]) != -1) {
		s += str[i];
      } else {
		if (s.size() == 0) {
          cr += str[i];
          continue;
		}
		flag = false;
      }

      // if s hold a word
      if (flag && i+1<str.size()) continue;

      if (sp.is_word(s)) {
		cr += s;
      } else {
		vector<string> sug = sp.get_suggestion(s);
          
		int count = 0;
		while(1) {
          cout << "The word: " << s << " is not in the language" << endl << endl;
          cout << str << endl;
          for (int k=0; k+s.size()<i; k++) cout << " ";
          for (int k=0; k<s.size(); k++) cout << "=";
          cout << endl << endl;
            
          cout << "a) Accept" << endl;
          cout << "r) Replace" << endl;
          if (sug.size()>=count+1) cout << "1) " << sug[count] << endl;
          if (sug.size()>=count+2) cout << "2) " << sug[count+1] << endl;
          if (sug.size()>=count+3) cout << "m) more" << endl;

          string opstr;
          cin >> opstr;
          if (opstr.size() <= 0) continue;
          char op = opstr[0];
            
          string tmp;
          switch (op) {
          case 'a':
			cr += s; break;
          case 'r':
			cout << "Enter your replacement: ";
			cin >> tmp;
			cr += tmp;
			break;
          case '1':
			if (sug.size() < 1) continue;
			cr += sug[count]; break;
          case '2':
			if (sug.size() < 2) continue;
			cr += sug[count+1]; break;
          case 'm':
			count += 2;
          default:
			continue;
          }
          break;
		}
      }
      cr += str[i];
      s.clear();
    }

	ofile << cr << endl;
  }

  ofile.close();
  text.close();

  return 0;
}
